import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import io, { Socket } from 'socket.io-client';
import { baseURL } from '@/utils/request';
import { GetToken } from '@/utils/storage';
import { useHistory } from 'react-router-dom';
import { Toast } from 'antd-mobile';

type ChatMsgType = {
  type: string;
  msg: string;
  timestamp: number;
}[];

export default function Chat() {
  const { userInfo } = useAppSelector((state) => state.user);
  const [msg, setMsg] = useState('');
  const [msgList, setMsgList] = useState<ChatMsgType>([]);
  const ClientRef = useRef<Socket | null>(null);
  const history = useHistory();
  useEffect(() => {
    /** 获取不到name值时重定向到个人中心页 */
    if (!userInfo.name) return history.push('/profile');

    ClientRef.current = io(baseURL, {
      transports: ['websocket'],
      query: {
        token: GetToken().token,
      },
    });
    /** 监听是否开启成功 */
    ClientRef.current.on('connect', () => {
      setMsgList([
        {
          msg: `您好,亲爱的${userInfo.name},小智为您服务!`,
          type: 'robot',
          timestamp: Date.now(),
        },
      ]);
    });
    /** 监听机器人回复事件 */
    ClientRef.current.on('message', (message) => {
      setMsgList((msgList) => [...msgList, { ...message, type: 'robot' }]);
    });
    /** 组件销毁时关闭ws链接 */
    return () => {
      ClientRef.current?.close();
    };
    // eslint-disable-next-line
  }, []);

  /** 监听屏幕可视高度使屏幕平滑滚动到最底部 */
  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [msgList]);

  /** 发送事件 */
  const handleSendMsg = () => {
    if (msg.trim()) {
      const userMsg = { msg, timestamp: Date.now() };
      ClientRef.current?.emit('message', userMsg);
      setMsgList([...msgList, { ...userMsg, type: 'user' }]);
      setMsg('');
    } else {
      Toast.show('不能发送空消息');
    }
  };

  /** 回车事件 */
  const handleEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') handleSendMsg();
  };

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {msgList.map((item, index) => {
          return (
            <div
              className={classNames('chat-item', {
                user: item.type === 'user' && 'user',
              })}
              key={index}
            >
              {item.type === 'robot' && <Icon type="iconbtn_xiaozhitongxue" />}
              {item.type === 'user' && <img src={userInfo.photo} alt="" />}
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Icon type="iconbianji" />
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onKeyDown={(e) => handleEnter(e)}
            onChange={(e) => setMsg(e.target.value)}
          />

          <span className="send" onClick={handleSendMsg}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
